package com.example.appforphysician.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
import android.widget.Toast;

public class ParseJson {
	String serverURL = "http://localhost:19705/HomeHealth/Patient?id=1";
	//String serverURL = "http://androidexample.com/media/webservice/JsonReturn.php";
	private  HttpClient Client = new DefaultHttpClient();
    private String Content;
    private String Error = null;
    String data =""; 
    int sizeData = 0; 
    BufferedReader reader=null;
	public ParseJson(){
		
		/*****************************************************/
		try {
			data  =URLEncoder.encode("data", "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ConnectServer();
	}
	
	public void ConnectServer(){
	
		try
		{ 
		   // Defined URL  where to send data
		   URL url = new URL(serverURL);
		   
		   
//		   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//		   conn.setRequestMethod("GET");
//		   conn.setRequestProperty("Accept", "application/json");
//
//		   if (conn.getResponseCode() != 200) {
//				throw new RuntimeException("Failed : HTTP error code : "
//						+ conn.getResponseCode());
//			}
	 
		
		  // Send POST data request
		
		  URLConnection conn = url.openConnection(); 
		  conn.setDoOutput(true); 
		  OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
		  wr.write( data ); 
		  wr.flush(); 
		
		  // Get the server response 
		   
		  reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		  StringBuilder sb = new StringBuilder();
		  String line = null;
		  
		 
		    // Read Server Response
		    while((line = reader.readLine()) != null)
		        {
		               // Append server response in string
		               sb.append(line + "\n");
		        }
		    
		    // Append Server Response To Content String 
		   Content = sb.toString();
		   
		   
		}
		catch(Exception ex)
		{
			Error = ex.getMessage();
		}
		finally
		{
		    try
		    {
		
		        reader.close();
		    }
		
		    catch(Exception ex) {}
		}
		
		
	    Log.e("JSON parse", "nd json"+Content); 
		
	}
	
	public String  ParseData(){
		/****************** Start Parse Response JSON Data *************/
    	
//    	String OutputData = "";
//        JSONObject jsonResponse;
//        Log.e("JSON parse", "nd json"+Content);     
//        try {
//           /*   
//             // ****** Creates a new JSONObject with name/value mappings from the JSON string. ******** /
//             jsonResponse = new JSONObject(Content);
//             
//             // ***** Returns the value mapped by name if it exists and is a JSONArray. *** /
//             // *******  Returns null otherwise.  ******* /
//             //JSONArray jsonMainNode = jsonResponse.optJSONArray("Address");
//             // *********** Process each JSON Node ************ /
//           */
//             JSONArray jsonMainNode = new JSONArray(Content);
//             int lengthJsonArr = jsonMainNode.length();  
//             Log.e("JSON parse", "aaa"+lengthJsonArr);
//             for(int i=0; i < lengthJsonArr; i++) 
//             {
//                // / ****** Get Object for each JSON node.*********** /
//                 JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
//                  
//                // / ******* Fetch node values ********** /
//                 String name       = jsonChildNode.optString("Address").toString();
//                 String number     = jsonChildNode.optString("CreateDate").toString();
//                 String date_added = jsonChildNode.optString("DateOfBirth").toString();
//                  
//                
//                 OutputData += " Address 		    : "+ name +" \n "
//                             + "CreateDate 		: "+ number +" \n "
//                             + "DateOfBirth 				: "+ date_added +" \n " 
//                             +"--------------------------------------------------\n";
//                
//                 //Log.i("JSON parse", song_name);
//            }
         /// ****************** End Parse Response JSON Data *************    
             
             //Show Parsed Output on screen (activity)
         //    jsonParsed.setText( OutputData );
//             
//              
//         } catch (JSONException e) {
//        	 Log.e("JSON parse", "aaa1");
//             e.printStackTrace();
//         }
//
//         return OutputData;
		
		return Content;
	}
	
	public JSONArray getPersonsData() throws ClientProtocolException, IOException, JSONException
    {
		String URL = serverURL;
        HttpGet get = new HttpGet(URL);
        HttpResponse response = Client.execute(get);
        int status = response.getStatusLine().getStatusCode();
 
        if(status == 200) //sucess
        {
            HttpEntity e = response.getEntity();
            String data = EntityUtils.toString(e);
            Content = data;
            JSONArray personsData = new JSONArray(data);
 
            return personsData;
        }
        else
        {
           
 
            return null;
        }
 
    }
	public String getContent()throws ClientProtocolException, IOException, JSONException{

		String URL = "http://localhost:19705/HomeHealth/Patient";
        HttpGet get = new HttpGet(URL);
        HttpResponse response = Client.execute(get);
     // make web service connection
//        HttpPost request = new HttpPost(serverURL);
//        request.setHeader("Accept", "application/json");
//        request.setHeader("Content-type", "application/json");


        // Get the status of web service
        BufferedReader rd = new BufferedReader(new InputStreamReader(
                     response.getEntity().getContent()));
        // print status in log
        String line = "";
        while ((line = rd.readLine()) != null) {
              Log.e("****Status Line***", "Webservice: " + line);

        }
        return line;
	}
	
	public String getAllToDoItems() {
        String result = "";
        try {
            // GET request to <service>/GetAllToDoItems
            // Gets all ToDoItems 
            HttpGet request = new HttpGet(serverURL );
            request.setHeader("Accept", "application/json");
            request.setHeader("Content-type", "application/json");

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse response = httpClient.execute(request);

            HttpEntity responseEntity = response.getEntity();

            // Read response data into buffer
            char[] buffer = new char[(int) responseEntity.getContentLength()];
            InputStream stream = responseEntity.getContent();
            InputStreamReader reader = new InputStreamReader(stream);
            reader.read(buffer);
            stream.close();

            result = new String(buffer);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.e("****Status buffer***", "Webservice: " + result);
        return result;
    }
	
	

}
